package com.itheima.travel.service.impl;

import com.itheima.travel.mapper.SellerMapper;
import com.itheima.travel.pojo.Seller;
import com.itheima.travel.pojo.SellerExample;
import com.itheima.travel.req.SellerVo;
import com.itheima.travel.service.SellerService;
import com.itheima.travel.session.SubjectSeller;
import com.itheima.travel.session.SubjectSellerContext;
import com.itheima.travel.utils.BeanConv;
import com.itheima.travel.utils.MD5Coder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

/**
 * @Description 商家服务类
 */
@Service
public class SellerServiceImpl implements SellerService {

    @Autowired
    private SellerMapper sellerMapper;

    //处理用户的session工具
    @Autowired
    private SubjectSellerContext subjectSellerContext;

    /**
     *  商家注册
     * @param sellerVo
     * @return  注册是否成功
     */
    @Override
    public Boolean registerSeller(SellerVo sellerVo) {

        Seller seller = BeanConv.toBean(sellerVo, Seller.class);
        seller.setPassword(MD5Coder.md5Encode(seller.getPassword()));
        int insert = sellerMapper.insert(seller);
        return insert>0;
    }

    /**
     * @Description 商家登录
     * @param sellerVo
     * @return  登录成功后返回
     */
    @Override
    public SellerVo loginSeller(SellerVo sellerVo) {

        //组装条件
        SellerExample sellerExample = new SellerExample();
        sellerExample.createCriteria()
                .andUsernameEqualTo(sellerVo.getUsername())
                .andPasswordEqualTo(MD5Coder.md5Encode(sellerVo.getPassword()));
        //查询list结果集
        List<Seller> sellerList = sellerMapper.selectByExample(sellerExample);
        if (sellerList.size() > 0){
            Seller seller = sellerList.get(0);
            //转换VO
            SellerVo sellerResult = BeanConv.toBean(seller, SellerVo.class);
            //登录成功后将用户对象放入会话
            String token = UUID.randomUUID().toString();
            // 将token存放到响应结果对象中(为的是下一次请求时携带token,这样才能从session中获取对应的数据信息)
            sellerResult.setToken(token);
            // vo: 与web层的业务一一对应
            subjectSellerContext.createdSubject(token,BeanConv.toBean(sellerResult, SubjectSeller.class));
            return sellerResult;
        }
        return null;
    }

    /**
     * @Description 商家退出
     */
    @Override
    public void loginOutUser() {
        //从会话中删除当前对象
        subjectSellerContext.deleteSubject();
    }

    /**
     * @Description 商家是否登录
     * @return  商家是否登录t
     */
    @Override
    public Boolean isLogin() {
        //根据当前用户是否存在判断登录状态
        return subjectSellerContext.existSubject();
    }
}
